import express from 'express'
import fs from 'node:fs/promises'
import path from 'node:path';
import {render} from './dist/server/entry-server.js'
import { get_template } from './src/lib/template.js'
const port = process.env.PORT || 3000

// Create http server
const app = express()
// console.log("aaa",path.join(import.meta.dirname, 'src'))
// let baseDir = path.dirname(import.meta.dirname)
// console.log(">>>>>",import.meta.dirname)

app.use('/',express.static(path.join(import.meta.dirname, 'dist','client')))
// Serve HTML
app.use('/', async (req, res) => {
    console.log("originalUrl is ",req.originalUrl)
    console.log(import.meta.dirname)
    let url=req.originalUrl
    // let template= await fs.readFile('./src/assets/template.html', 'utf-8')
    let template= get_template(import.meta.dirname)
    console.log("template >>> ",template)
    // console.log(template)
    const { stream } = render(url)

    const [htmlStart, htmlEnd] = template.split('<!--app-html-->')

    res.status(200).set({ 'Content-Type': 'text/html' })
    
    res.write(htmlStart)
    for await (const chunk of stream) {
      if (res.closed) break
      // console.log(chunk.toString('utf8'))
      res.write(chunk)
    }
    res.write(htmlEnd)
    res.end()
})
// app.use(express.static(path.dirname(import.meta.dirname)))

// Start http server
app.listen(port, () => {
    console.log(`Server started at http://localhost:${port}`)
})